<?php

namespace Data;

class Article extends Base {
    /**
     * 添加文章
     *
     * @param $data
     *
     * @return mixed返回Id
     */
    public function addArticle($data) {
        $id = $this->instance()->Insert($data);
        return $id;
    }

    /**
     * 根据Id获取文章详情
     *
     * @param $id 文章Id
     *
     * @return array 返回文章详情数组
     */
    public function getArticleById($id) {
        $where = array('Id' => $id);
        $info = $this->where($where)->findOne();
        return $info;
    }

    /**
     * 根据Id修改文章信息
     *
     * @param $id 文章Id
     *
     * @param $data 文章信息
     */
    public function updateArticle($id, $data) {
        $where = array('Id' => $id);
        $this->where($where)->update($data);
    }

    /**
     * 根据Id删除文章
     *
     * @param $id
     */
    public function delArticleById($id) {
        $where = array('Id' => $id);
        $this->where($where)->del();
    }

    /**
     * 根据分类Id获取文章
     *
     * @param $categoryId
     * @param $pager
     * @return array
     */
    public function getAllArticleByCategoryId($categoryId, $pager) {
        if(is_array($categoryId)) {
            $where = array('CategoryId in ' => $categoryId);
        } else {
            $where = array('CategoryId ' => $categoryId);
        }
        return $this->where($where)->pager($pager)->findAll();
    }

    public function getArticleIdByCategoryId($categoryId) {
        $where = array('CategoryId ' => $categoryId);
        $res =  $this->select('Id')->where($where)->order('Id DESC')->findOne();
        return $res ? $res['Id'] : 0;
    }

    public function getList($pager, $categoryId) {
        $condition = array(
            'CategoryId' => $categoryId,
            'Status' => \Data\Base::IS_YES,
        );
        return $this->where($condition)->order('Sort desc, Id Desc')->pager($pager)->findAll();
    }

    /**
     * 根据分类Id获取文章
     * @param $categoryIds
     * @param int $count
     * @return array
     */
    public function getAllArticleByCategoryIds($categoryIds, $count = 1){
        $where = array('Status' => self::IS_YES, 'CategoryId in' => $categoryIds);
        return $this->where($where)->order('CreateTime DESC')->limit($count)
            ->findAll();
    }
}